package com.lanwf.admin.sys.account;

import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.lanwf.admin.BaseController;
import com.lanwf.IAdminIndexController;
import com.lanwf.admin.sys.PermissionService;
import com.lanwf.common.model.SysAdmin;
import com.lanwf.common.model.SysMenu;
import com.lanwf.common.model.SysPermission;
import com.lanwf.admin.utils.CommonUtil;
import com.lanwf.admin.utils.Cons;
import com.lanwf.admin.utils.Result;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Auther: Lanwf
 * @Date: 2021/12/24 10:55
 * @Description:
 */
@Path(value = "/admin/account", viewPath = "/admin/sys/account")
public class AccountAdminController extends BaseController implements IAdminIndexController {

    @Inject
    PermissionService permissionService;

    @Override
    public void index() {

        set("permission",permissionService.getPermission(getAccountId(),getInt(0)));
        render("index.html");
    }

    @Override
    public void paginate() {
        Integer p = getInt("pageNum", 1);
        Integer s = getInt("pageSize", 10);

        String orderByColumn = get("orderByColumn", "");
        String isAsc = get("isAsc", "");

        String name = get("nickname", "");
        Integer status = getInt("status", -1);
        Integer sex = getInt("sex", -1);

        List<Object> param = new ArrayList<>();

        String sql = "";
        if(getAccountId() == 1 ){
            sql = " from sys_admin where 1=1 ";
        }else{
            sql = " from sys_admin where id > 1 ";
        }


        if (StrKit.notBlank(name)) {
            sql += " and nickname like ? or username like ? ";
            param.add("%" + name + "%");
            param.add("%" + name + "%");
        }

        if (status > -1) {
            sql += " and status = ? ";
            param.add(status);
        }

        if (sex > -1) {
            sql += " and sex = ? ";
            param.add(sex);
        }

        sql += " order by ";

        if (StrKit.notBlank(orderByColumn)) {
            sql += "" + orderByColumn + " " + isAsc;
        }

        Page<SysAdmin> paginate = SysAdmin.dao.paginate(p, s, "select *", sql, param.toArray());

        paginate.getList().forEach(a -> {
            if (StrKit.notBlank(a.getAvatar())) {
                a.setAvatar(Cons.prj + a.getAvatar());
            } else {
                a.setAvatar(Cons.prj + "/assets/static/img/profile.jpg");
            }
        });

        renderJson(new Result<>(paginate.getTotalRow(), paginate.getList()));
    }

    @Override
    public void add() {
        render("add_edit.html");
    }

    @Override
    public void save() {
        getFile();
        SysAdmin model = getModel(SysAdmin.class, "adm");
        model.set("create_time", new Date()).save();

        String permission = getRequest().getParameter("permission");
        if (StringUtils.isNotBlank(permission)) {

            ArrayList<SysPermission> list = new ArrayList<>();
            String[] split = permission.split(",");
            String tempB = "";
            String tempC = "";

            for (String s : split) {
                if (s.contains("b")) {
                    tempB += s.replace("b", "") + ",";
                }
                if (s.contains("_")) {
                    tempC += s + ",";
                }
            }
            tempB = tempB.substring(0, tempB.lastIndexOf(","));
            tempC = tempC.substring(0, tempC.lastIndexOf(","));

            HashMap<String, SysMenu> setData = new HashMap<>();
            List<SysMenu> sysMenus = SysMenu.dao.find("select * from sys_menu");
            for (SysMenu sysMenu : sysMenus) {
                setData.put(sysMenu.getId().toString(), sysMenu);
            }

            String[] split2 = tempB.split(",");
            for (String s1 : split2) {
                SysMenu sysMenu = setData.get(s1);

                SysPermission p = new SysPermission();

                p.setPid(sysMenu.getPid());
                p.setAccountId(model.getId());
                p.setMenuId(Integer.valueOf(s1));


                String operates = "";
                if (StringUtils.isNotBlank(tempC)) {

                    String[] split3 = tempC.split(",");
                    for (String s2 : split3) {
                        String[] split4 = s2.split("_");
                        if (split4[0].equals(s1)) {
                            operates += split4[1] + ",";
                        }
                    }
                    if(StringUtils.isNotBlank(operates)){
                        operates = operates.substring(0,operates.lastIndexOf(","));
                    }

                }
                p.setOperates(operates);
                list.add(p);
            }

            Db.delete("delete from sys_permission where account_id = ? ",model.getId());
            Db.batchSave(list,2000);

            CommonUtil.setCache("listMenus",null);
        }


        renderJson(Ret.ok().set("msg", "添加成功"));
    }

    @Override
    public void edit() {
        Integer id = getInt(0);
        SysAdmin account = SysAdmin.dao.findById(id);
        set("adm", account);
        render("add_edit.html");
    }

    @Override
    public void update() {
        getFile();
        SysAdmin model = getModel(SysAdmin.class, "adm");
        String permission = getRequest().getParameter("permission");

        if (StringUtils.isNotBlank(permission)) {

            ArrayList<SysPermission> list = new ArrayList<>();
            String[] split = permission.split(",");
            String tempB = "";
            String tempC = "";

            for (String s : split) {
                if (s.contains("b")) {
                    tempB += s.replace("b", "") + ",";
                }
                if (s.contains("_")) {
                    tempC += s + ",";
                }
            }
            if(StringUtils.isNotBlank(tempB)){
                tempB = tempB.substring(0, tempB.lastIndexOf(","));
            }
            if(StringUtils.isNotBlank(tempC)){
                tempC = tempC.substring(0, tempC.lastIndexOf(","));
            }

            HashMap<String, SysMenu> setData = new HashMap<>();
            List<SysMenu> sysMenus = SysMenu.dao.find("select * from sys_menu");
            for (SysMenu smenu : sysMenus) {
                setData.put(smenu.getId().toString(), smenu);
            }

            String[] split2 = tempB.split(",");
            for (String s1 : split2) {
                SysMenu smenu = setData.get(s1);

                SysPermission p = new SysPermission();

                p.setPid(smenu.getPid());
                p.setAccountId(model.getId());
                p.setMenuId(Integer.valueOf(s1));


                String operates = "";
                if (StringUtils.isNotBlank(tempC)) {

                    String[] split3 = tempC.split(",");
                    for (String s2 : split3) {
                        String[] split4 = s2.split("_");
                        if (split4[0].equals(s1)) {
                            operates += split4[1] + ",";
                        }
                    }
                    if(StringUtils.isNotBlank(operates)){
                        operates = operates.substring(0,operates.lastIndexOf(","));
                    }

                }
                p.setOperates(operates);
                list.add(p);
            }

            Db.delete("delete from sys_permission where account_id = ? ",model.getId());
            Db.batchSave(list,2000);

            CommonUtil.setCache("listMenus",null);
        }


        if(model.getId() == 1){
            model.setStatus(0);
        }
        model.update();
        renderJson(Ret.ok().set("msg", "修改成功"));
    }

    @Override
    public void delete() {
        Integer id = getInt(0);
        SysAdmin.dao.deleteById(id);
        renderJson(Ret.ok().set("msg", "删除成功"));
    }

    /**
     * 更新后台密码
     */
    public void updatePassword() {
        Integer id = getInt("id");
        String password = get("password");
        SysAdmin p = new SysAdmin();
        p.setId(id);
        p.setPassword(password);
        p.update();
        renderJson(Ret.ok().set("msg", "密码修改成功"));
    }

    /**
     * 修改密码
     */
    public void resetPwd() {
        set("account", getAccount());
    }

    /**
     * 个人中心页面
     */
    public void profile() {
    }

    /**
     * 头像页面
     */
    public void avatar() {

    }

    /**
     * 更新头像
     */
    public void updateAvatar() throws IOException {
        UploadFile uploadFile = getFile("avatarfile", Cons.AVATAR);

        File file = uploadFile.getFile();

        FileInputStream ins = new FileInputStream(file);

        String imgName = CommonUtil.getUUIDToLower() + ".jpg";
        FileOutputStream ous = new FileOutputStream(PathKit.getWebRootPath() + "/upload" + Cons.AVATAR + imgName);

        byte[] bytes = new byte[1024];

        int len = -1;
        while ((len = ins.read(bytes)) > -1) {
            ous.write(bytes, 0, len);
            ous.flush();
        }

        ous.close();
        ins.close();

        file.delete();

        SysAdmin account = getAccount();
        account.setAvatar("/upload" + Cons.AVATAR + imgName);
        account.update();
        renderJson(Ret.ok().set("msg", "修改成功"));
    }

    /**
     * 账户唯一判定
     */
    public void usernameUnique() {
        Integer id = getInt("id");
        String username = get("username", "");

        SysAdmin first = null;
        if (id != null) {
            first = SysAdmin.dao.findFirst("select * from sys_admin where id != ? and username = ? ", id, username);

        } else {
            first = SysAdmin.dao.findFirst("select * from sys_admin where username = ? ", username);

        }
        if (first != null) {
            renderJson(Ret.fail("msg", "账户已重复"));
            return;
        }

        renderJson(Ret.ok("msg", "账户可用"));
    }

    /**
     * 修改密码
     */
    public void resetPassword() {
        String newPassword = get("newPassword");
        SysAdmin.dao.findById(getAccountId()).set("password", newPassword).update();
        renderJson(Ret.ok("msg", "修改成功"));
    }

    /**
     * 修改密码
     */
    public void resetUserInfo() {
        SysAdmin.dao.findById(getAccountId()).set("nickname", get("nickname")).set("sex",get("sex")).update();
        renderJson(Ret.ok("msg", "修改成功"));
    }


    /**
     * 上锁
     */
    public void onLock() {
        SysAdmin.dao.findById(getInt("id")).set("status", 1).update();
        renderJson(Ret.ok("msg", "上锁成功"));
    }

    /**
     * 解锁
     */
    public void offLock() {
        SysAdmin.dao.findById(getInt("id")).set("status", 0).update();
        renderJson(Ret.ok("msg", "解锁成功"));
    }

}

